package com.hctforgreen.greenservice;

import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.taptwo.android.widget.MyXListView;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.Service;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.hctforgreen.greenservice.ctr.HctBackTestJsonController;
import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.db.DBManager;
import com.hctforgreen.greenservice.model.PwdEntity;
import com.hctforgreen.greenservice.model.SpareBootPasswordEntity;
import com.hctforgreen.greenservice.model.SubmitBigUnitInfoEntity;
import com.hctforgreen.greenservice.ui.adapter.HisPwdListAdapter;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.HctResult;
import com.hctforgreen.greenservice.utils.LoginResultStoreUtil;
import com.hctforgreen.greenservice.utils.Utils;
import com.hctforgreen.greenservice.utils.irremote.GoogleIrDevice;
import com.hctforgreen.greenservice.utils.irremote.GreeIrFcode;

/**
 * 历史记录
 * 
 * @author ld 20140403
 * 
 */
public class HisRecordActivity extends ParentActivity implements
		OnClickListener {
	private Button search_btn;
	private TextView date_end_edit;
	private TextView date_start_edit;
	private TextView date_edit;// 记录当前是哪个控件调用时间控件
	private TextView stripeCode_edit;
	private static final int DATE_DIALOG_ID = 1;
	private static final int SHOW_DATAPICK = 0;
	private int mYear;
	private int mMonth;
	private int mDay;
	private DBManager mgr;
	private Activity context;
	private MyXListView xListView;
	private HisPwdListAdapter mHisPwdListAdapter;
	private List<PwdEntity> pwds;
	private TextView no_data_txt;
	private ProgressBar loadPb;
	/*编码规则和发码类
     * 
     */
    public static GreeIrFcode greeFcode;
    public static GoogleIrDevice googleIrDev;
    private Vibrator vibrator;
	private int times = 1000*3;
	
	/**
	 * 登录标识，用于判断登录掌上通正式服务器的次数，超过1次则判断为正式服务器宕机
	 */
	public int pingCount = 0;
	
	/**
	 * false为正式服务器，true为云服务器
	 */
	private boolean isCloudServer = false;
    
	@Override
	protected void onResume() {
		super.onResume();
		initSkinLayout();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = this;
		setContentView(R.layout.activity_his_record);
//		greeFcode=new GreeIrFcode();
//		googleIrDev=new GoogleIrDevice(context);
		final TextView titleTv = (TextView) findViewById(R.id.tv_title);
		titleTv.setText(getString(R.string.title_his_record));

		final ImageButton btn_back = (ImageButton) findViewById(R.id.btn_back);
		btn_back.setOnClickListener(mOnClick);

		loadPb = (ProgressBar) findViewById(R.id.pb_loading);

		date_end_edit = (TextView) findViewById(R.id.date_end_edit);
		date_end_edit.setOnClickListener(mOnClick);

		date_start_edit = (TextView) findViewById(R.id.date_start_edit);
		date_start_edit.setOnClickListener(mOnClick);

		stripeCode_edit = (TextView) findViewById(R.id.stripeCode_edit);

		search_btn = (Button) findViewById(R.id.search_btn);
		search_btn.setOnClickListener(mOnClick);
		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);
		// setDateTime();
		no_data_txt = (TextView) findViewById(R.id.no_data_txt);

		xListView = (MyXListView) findViewById(R.id.xListView);
		xListView.setPullLoadEnable(false);
		xListView.setPullRefreshEnable(false);
		
		pingCount = getIntent().getIntExtra("PING_COUNT", 0);
		isCloudServer = getIntent().getBooleanExtra("WHICH_SERVER", false);
		/*if(!HctBackTestJsonController.isB_DEBUG()){
			Log.i("DATA", "传到MainActivityV2的--pingCount   " + pingCount);
			Log.i("DATA", "传到MainActivityV2的--isClounServer   " + isCloudServer);
		}*/
		
		mgr = new DBManager(context);
		pwds = mgr.queryAll();
		autoCompleteForBigUnit();
		mHisPwdListAdapter = new HisPwdListAdapter(context, pwds, mOnClick, mgr);
		xListView.setAdapter(mHisPwdListAdapter);
		status(pwds);
	}

	/**
	 * 调用报完成接口将已查看的拒绝申请的记录自动报完成,防止服务器把历史记录里已删除的拒绝申请机型的数据再次传给客户端造成错误统计
	 */
	private void autoCompleteForBigUnit() {
		if (!pwds.isEmpty()) {
			for (int i = 0; i < pwds.size(); i++) {
				if (pwds.get(i).verifyStatus.equals("2")) {
					submitBigUnitAutoComplete(
							LoginResultStoreUtil.get(context).personId,
							LoginResultStoreUtil.get(context).phone,
							pwds.get(i).identityCode, pwds.get(i).stripeCode,
							"1");
				}

			}
		}

	}

	/**
	 * 设置状态
	 * 
	 * @param pwds
	 */
	private void status(List<PwdEntity> pwds) {
		if (pwds == null || pwds.size() <= 0) {
			no_data_txt.setVisibility(View.VISIBLE);
			xListView.setVisibility(View.GONE);
		} else {
			no_data_txt.setVisibility(View.GONE);
			xListView.setVisibility(View.VISIBLE);
		}
	}

	/**
	 * 设置现在时间
	 */
	private void setDateTime() {
		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);
		updateDisplay();
	}

	/**
	 * 更新日期
	 */
	private void updateDisplay() {
		String newDate = new StringBuilder()
				.append(mYear)
				.append((mMonth + 1) < 10 ? "-0" + (mMonth + 1)
						: ("-" + (mMonth + 1)))
				.append((mDay < 10) ? "-0" + mDay : "-" + mDay).toString();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		String date_end = (String) date_end_edit.getText();
		String date_start = (String) date_start_edit.getText();
		try {
			if (date_edit == date_start_edit && !date_end.equals("")) {
				if (sdf.parse(newDate).getTime() <= sdf.parse(date_end)
						.getTime()) {
					date_edit.setText(newDate);
				} else {
					Toast.makeText(context, "开始时间不能大于结束时间！", Toast.LENGTH_SHORT)
							.show();
				}
			} else if (date_edit == date_end_edit && !date_start.equals("")) {
				if (sdf.parse(newDate).getTime() >= sdf.parse(date_start)
						.getTime()) {
					date_edit.setText(newDate);
				} else {
					Toast.makeText(context, "结束时间不能小于开始时间！", Toast.LENGTH_SHORT)
							.show();
				}
			} else {
				date_edit.setText(newDate);
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		/*
		 * date_edit.setText(new StringBuilder() .append(mYear) .append((mMonth
		 * + 1) < 10 ? "-0" + (mMonth + 1) : ("-" + (mMonth + 1))) .append((mDay
		 * < 10) ? "-0" + mDay : "-" + mDay));
		 */
	}

	/**
	 * 日期控件的事件
	 */
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			updateDisplay();
		}

	};

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);
		}
		return null;

	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
		case DATE_DIALOG_ID:
			((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
			// 设置控件最大最小时间，会有bug
			/*
			 * try { String startDate = date_start_edit.getText().toString();
			 * String endDate = date_end_edit.getText().toString();
			 * SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); Date
			 * curDate = new Date(System.currentTimeMillis());//获取当前时间
			 * if(date_edit == date_start_edit){
			 * //点击开始时间按钮时，如果结束时间不为空，则最大时间为结束时间 long maxDate =
			 * endDate.equals("")?
			 * curDate.getTime():sdf.parse(endDate).getTime();
			 * ((DatePickerDialog) dialog).getDatePicker().setMaxDate(maxDate);
			 * ((DatePickerDialog) dialog).getDatePicker().setMinDate(0); }else{
			 * //点击结束时间按钮时，如果开始时间不为空，则最小时间为开始时间 if(!startDate.equals("")){
			 * ((DatePickerDialog)
			 * dialog).getDatePicker().setMinDate(sdf.parse(startDate
			 * ).getTime()); } ((DatePickerDialog)
			 * dialog).getDatePicker().setMaxDate(curDate.getTime());//最大时间设为当天
			 * }
			 * 
			 * } catch (ParseException e) { e.printStackTrace(); }
			 */
			break;
		}
	}

	/**
	 * 处理日期控件的Handler
	 */
	Handler saleHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SHOW_DATAPICK:
				showDialog(DATE_DIALOG_ID);
				break;
			}
		}
	};
	int sel_p;
	private OnClickListener mOnClick = new OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.btn_back:
				finish();
				break;
			case R.id.date_start_edit:
				Message msg = new Message();
				msg.what = SHOW_DATAPICK;
				date_edit = date_start_edit;
				saleHandler.sendMessage(msg);
				break;
			case R.id.date_end_edit:
				Message msg1 = new Message();
				msg1.what = SHOW_DATAPICK;
				date_edit = date_end_edit;
				saleHandler.sendMessage(msg1);
				break;
			case R.id.search_btn:

				String date_start = date_start_edit.getText().toString().trim();
				String date_end = date_end_edit.getText().toString().trim();
				String stripeCode = stripeCode_edit.getText().toString().trim();
				Map param = new HashMap();
				param.put("date_start", date_start);
				param.put("date_end", date_end);
				param.put("stripeCode", stripeCode);
				pwds.clear();
				pwds.addAll(mgr.queryByDate(param));
				mHisPwdListAdapter.notifyDataSetChanged();
				status(pwds);
				break;
			case R.id.del_btn:
				Utils.notice(context, "提示", "是否删除该记录", ok_click, null);
				sel_p = (Integer) v.getTag();
				if (mHisPwdListAdapter.isBigUnit(pwds.get(sel_p).stripeCode)) {
					submitBigUnitAutoComplete(
							LoginResultStoreUtil.get(context).personId,
							LoginResultStoreUtil.get(context).phone,
							pwds.get(sel_p).identityCode,
							pwds.get(sel_p).stripeCode, "1");
				}

				break;
			case R.id.bigUnit_complete_btn:
				Log.i("DATA", "报完成--------1");
				// Utils.notice(context, "提示", "是否要报完成", ok_click, null);
				sel_p = (Integer) v.getTag();
				pwds.get(sel_p).finished = "1";

				// 大机组调试报完成提交数据至服务器
				String personId = LoginResultStoreUtil.get(context).personId;
				String phone = LoginResultStoreUtil.get(context).phone;
				String identityCode = pwds.get(sel_p).identityCode;
				String stripeCode2 = pwds.get(sel_p).stripeCode;
				String finished = pwds.get(sel_p).finished;
				submitBigUnitComplete(personId, phone, identityCode,
						stripeCode2, finished, isCloudServer);

				break;
			case R.id.link_backuppwd:
				// Utils.notice(context, "提示", "是否获取备用密码",
				// link_backuppwd_click(), null);
				sel_p = (Integer) v.getTag();
				link_backuppwd_click(v);
				break;
				
			case R.id.button_sentPassword:
			//设置发送红外密码点击事件
				sel_p = (Integer) v.getTag();
				sentPassword_click(v);
				
				break;
			default:
				break;
			}
		}
	};

	/**
	 * 
	 * 调用报完成接口将已查看的拒绝申请的记录自动报完成，防止服务器把历史记录里已删除的拒绝申请机型的数据再次传给客户端造成错误统计
	 * 
	 * @param personId
	 *            ---登录的id
	 * @param phone
	 *            --登录账号
	 * @param identityCode
	 *            --身份码
	 * @param stripeCode
	 *            ---条形码
	 * @param finished
	 *            ---是否报完成
	 */
	public void submitBigUnitAutoComplete(final String personId,
			final String phone, final String identityCode,
			final String stripeCode, final String finished) {
		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					HctController controller = new HctController(context);
					HctResult result = new HctResult();
					result = controller.BigUnitComplete(personId, phone,
							identityCode, stripeCode, finished, isCloudServer);
					if (result.status == HctConstants.STATUS_SUCCESS) {
						message.what = HctConstants.STATUS_SUCCESS;
						message.obj = result;
					} else {
						message.what = HctConstants.STATUS_FAILD;
					}

				} catch (Exception e) {
					message.what = HctConstants.STATUS_FAILD;
					e.printStackTrace();
				}

			};
		}.start();

	}

	/**
	 * 大机组调试报完成
	 * 
	 * @param personId
	 *            ---登录的id
	 * @param phone
	 *            --登录账号
	 * @param identityCode
	 *            --身份码
	 * @param stripeCode
	 *            ---条形码
	 * @param finished
	 *            ---是否报完成
	 *            
	 * @param isCloudServer--是否是云服务器
	 */
	private void submitBigUnitComplete(final String personId,
			final String phone, final String identityCode,
			final String stripeCode, final String finished, final boolean isCloudServer) {
		final Handler handler = new Handler() {
			@SuppressWarnings("deprecation")
			public void handleMessage(Message msg) {
				Button complete_btn = (Button) (Button) findViewById(R.id.bigUnit_complete_btn);
				HctResult result = new HctResult();
				switch (msg.what) {
				case HctConstants.STATUS_SUCCESS:
					result = (HctResult) msg.obj;
					SubmitBigUnitInfoEntity mBigUnitPasswordEntity = (SubmitBigUnitInfoEntity) result.data;
					if (mBigUnitPasswordEntity.statusCode.equals("0")) {
						if (mBigUnitPasswordEntity.unitStatus.equals("0")) {
							Log.i("DATA", "调试报完成--修改verifyStatus");
							PwdEntity entity = pwds.get(sel_p);
							entity.verifyStatus = "3";
							mgr.updateCompleteStatus(entity);

							Toast.makeText(context,
									mBigUnitPasswordEntity.unitMsg,
									Toast.LENGTH_SHORT).show();
							complete_btn.setClickable(false);
							complete_btn.setText("调试已完成");
							complete_btn.setBackgroundDrawable(getResources()
									.getDrawable(R.drawable.ic_gray_rect_bg));
							mHisPwdListAdapter.notifyDataSetChanged();

						}
					} else if (!mBigUnitPasswordEntity.statusCode.equals("0")) {
						if (!mBigUnitPasswordEntity.unitMsg.equals("")) {
							Toast.makeText(context,
									mBigUnitPasswordEntity.unitMsg,
									Toast.LENGTH_SHORT).show();
							complete_btn.setClickable(true);
							complete_btn.setBackgroundDrawable(getResources()
									.getDrawable(R.drawable.btn_orange));
						} else if (mBigUnitPasswordEntity.unitMsg.equals("")) {
							Toast.makeText(
									context,
									getString(R.string.bigUnit_complete_failed),
									Toast.LENGTH_SHORT).show();
						}
					}

					break;
				case HctConstants.STATUS_FAILD:
					Toast.makeText(context,
							getString(R.string.bigUnit_complete_failed),
							Toast.LENGTH_SHORT).show();
					break;
				}

			}
		};

		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					HctController controller = new HctController(context);
					HctResult result = new HctResult();
					result = controller.BigUnitComplete(personId, phone,
							identityCode, stripeCode, finished, isCloudServer);
					if (result.status == HctConstants.STATUS_SUCCESS) {
						message.what = HctConstants.STATUS_SUCCESS;
						message.obj = result;
					} else {
						message.what = HctConstants.STATUS_FAILD;
					}

				} catch (Exception e) {
					message.what = HctConstants.STATUS_FAILD;
					e.printStackTrace();
				}
				handler.sendMessage(message);

			};
		}.start();

	}

	private void sentPassword_click(final View v) {
		final PwdEntity entity = pwds.get(sel_p);
		
		//整合密码list
		ArrayList<String> passwordList = new ArrayList<String>();
		passwordList.add(0, entity.openPassword);
		String[] backuppwdList = entity.sparebootPwd.toString().split("或");
		for (int i = 0; i < backuppwdList.length; i++) {
			if(!backuppwdList[i].isEmpty()){
				passwordList.add(backuppwdList[i].trim());
			}
		}
		int num=passwordList.size();
		final String[] ItemList = new String[num];
		for (int i = 0; i < passwordList.size(); i++) {
			ItemList[i] = passwordList.get(i);
			
		}
		
		if(ItemList.length>1){//多于一条则弹出选择框
			new AlertDialog.Builder(context)
			.setTitle("单选框")
			.setIcon(android.R.drawable.ic_dialog_info)
			.setSingleChoiceItems(
					ItemList, 0,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int which) {
							Log.d("ItemList[which]", ""+ItemList[which]);
							sendIrCode(ItemList[which]);
							dialog.dismiss();
						}
					}).setNegativeButton("取消", null).show();
		}else{
			sendIrCode(ItemList[0]);
		}
	}
	private void link_backuppwd_click(final View v) {
		final PwdEntity entity = pwds.get(sel_p);
		v.setClickable(false);
		loadPb.setVisibility(View.VISIBLE);
		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {

				loadPb.setVisibility(View.GONE);
				v.setClickable(true);
				HctResult hctResult = new HctResult();
				switch (msg.what) {
				case HctConstants.STATUS_SUCCESS:
					hctResult = (HctResult) msg.obj;
					SpareBootPasswordEntity bean = (SpareBootPasswordEntity) hctResult.data;
					if (bean.statusCode.equals("0")) {
						String sparebootPwd = bean.bootPwd.replace("[", "")
								.replace("]", "").replace("\"", "");
						// 保存备用密码到本地
						PwdEntity updateEntity = new PwdEntity();
						updateEntity = entity;
						updateEntity.sparebootPwd = sparebootPwd;
						mgr.updateSparebootPwd(updateEntity);

						// 根据条件刷新页面
						pwds.clear();
						String date_start = date_start_edit.getText()
								.toString().trim();
						String date_end = date_end_edit.getText().toString()
								.trim();
						String stripeCode = stripeCode_edit.getText()
								.toString().trim();
						Map param = new HashMap();
						param.put("date_start", date_start);
						param.put("date_end_edit", date_end_edit);
						param.put("stripeCode", stripeCode);
						pwds.addAll(mgr.queryByDate(param));
						mHisPwdListAdapter.notifyDataSetChanged();
						status(pwds);
					} else if (!bean.statusCode.equals("0")) {
						if (!bean.bootMsg.equals("")) {
							Toast.makeText(context, bean.bootMsg,
									Toast.LENGTH_SHORT).show();
						} else if (bean.bootMsg.equals("")) {
							Toast.makeText(context,
									context.getString(R.string.net_error_hint),
									Toast.LENGTH_SHORT).show();
						}

					}
					break;

				case HctConstants.STATUS_FAILD:
					Toast.makeText(context,
							context.getString(R.string.net_error_hint),
							Toast.LENGTH_SHORT).show();
					break;
				}

			}
		};
		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					HctController controller = new HctController(context);
					HctResult result = controller.getSpareBootPwd(entity, isCloudServer);
					if (result.status == HctConstants.STATUS_SUCCESS) {
						message.what = result.status;
						message.obj = result;
					} else {
						message.what = HctConstants.STATUS_FAILD;
					}
				} catch (Exception e) {
					message.what = HctConstants.STATUS_FAILD;
					e.printStackTrace();
				}
				handler.sendMessage(message);
			}
		}.start();
	}

	android.content.DialogInterface.OnClickListener ok_click = new android.content.DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface arg0, int arg1) {
			// TODO Auto-generated method stub
			mgr.deleteOldPwd(pwds.get(sel_p));
			pwds.remove(sel_p);
			mHisPwdListAdapter.notifyDataSetChanged();
			status(pwds);
		}
	};

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mgr.closeDB();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

	}
	
	/**
	 * 发送红外密码
	 * @param password
	 * @param v 
	 */
	private void sendIrCode(final String password){
		//手机震动
		greeFcode=new GreeIrFcode();
		googleIrDev=new GoogleIrDevice(context);
		vibrator = (Vibrator)context.getSystemService(Service.VIBRATOR_SERVICE);
		vibrator.vibrate(50);
				
		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
					case 1:
						Toast.makeText(context,
								"已发送密码："+msg.obj.toString(),
								Toast.LENGTH_SHORT).show();
						break;
					case 2:
						Toast.makeText(context,
								"红外发送密码："+msg.obj.toString()+"异常",
								Toast.LENGTH_SHORT).show();
						break;
				}
					
			}
		};
		
		
		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					//红外发射
					Log.d("hahha:", password);
					googleIrDev.sendIrCode(greeFcode.getRateFcodeStr(greeFcode.getPassCodeBytes(password)));
					message.what = 1;
					message.obj = password;
					handler.sendMessage(message);
				} catch (Exception e) {
					message = new Message();
					message.what = 2;
					message.obj = password;
					handler.sendMessage(message);
					e.printStackTrace();
				}finally{
					vibrator.cancel();
				}
			}
		}.start();
	}
}
